package com.unitechs.trap.excel.webapi.utils;

import lombok.extern.slf4j.Slf4j;
import org.bouncycastle.util.encoders.UTF8;

import java.io.BufferedReader;
import java.io.DataOutputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Slf4j
public class HttpPostRequestUtils {

    public static String trapHttpPostRequest(String url,String token,String json) {
        StringBuffer response = new StringBuffer();
        try {

            URL obj = new URL(url);
            HttpURLConnection con = (HttpURLConnection) obj.openConnection();

            //add request header
            con.setRequestMethod("POST");
            if (token==null||token.isEmpty()||token.equals("")){

            }else {
                con.setRequestProperty("zy_token", token);
            }
            con.setRequestProperty("Content-Type", "application/json");

            // Send post request
            con.setDoOutput(true);
            DataOutputStream wr = new DataOutputStream(con.getOutputStream());
            wr.writeBytes(json);
            wr.flush();
            wr.close();

            int responseCode = con.getResponseCode();

            BufferedReader in = new BufferedReader(new InputStreamReader(con.getInputStream()));
            String inputLine;


            while ((inputLine = in.readLine()) != null) {
                //将unicode转中文
                Pattern pattern = Pattern.compile("(?<first>\\\\u(?<secound>\\p{XDigit}{4}))");
                Matcher matcher =pattern.matcher(inputLine);
                char ch;
                while (matcher.find()){
                    ch=(char) Integer.parseInt(matcher.group("secound"),16);
                    inputLine=inputLine.replace(matcher.group("first"),ch+"" );
                }

                response.append(inputLine);
            }
            in.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

        return response.toString();
    }



}
